package com.linln.admin.pcs.api;

import com.alibaba.fastjson.JSONArray;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.linln.admin.config.IDCardEncryptor;
import com.linln.admin.config.SmsUtils;
import com.linln.admin.pcs.service.RsaService;
import com.linln.admin.pcs.service.TemplateMessageService;
import com.linln.admin.pcs.service.WeChatPayService;
import com.linln.admin.pcs.service.WechatPayRefundService;
import com.linln.admin.util.NetworkInfoUtil;
import com.linln.common.data.PageSort;
import com.linln.common.data.QuerySpec;
import com.linln.common.utils.DateUtils;
import com.linln.common.utils.HelperUtil;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.SnowflakeIdGenerator;
import com.linln.common.vo.ResultVo;
import com.linln.modules.system.domain.*;
import com.linln.modules.system.repository.*;
import com.linln.modules.system.service.*;
import com.linln.modules.system.util.WeChatPayUtil;
import com.msun.enums.AuthorizationKeyType;
import com.msun.util.OpenapiUtil;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 *患者接口
 */
@RestController
@RequestMapping("/api/patient/")
public class PatientApiController {
    private final static Logger logger = LoggerFactory.getLogger(PatientApiController.class);
    @Autowired
    private ProjectRepository projectRepository;

    @Autowired
    private PorterRepository porterRepository;

    @Autowired
    private PorterPermissionRepository porterPermissionRepository;

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private PorterCredentialsRepository porterCredentialsRepository;

    @Autowired
    private ProjectStageRepository projectStageRepository;

    @Autowired
    private PatientAdmissionRepository patientAdmissionRepository;

    @Autowired
    private PatientRepository patientRepository;

    @Autowired
    private PorterService porterService;

    @Autowired
    private OrderAmountsRepository orderAmountsRepository;

    @Autowired
    private MsgRepository msgRepository;

    @Autowired
    private EvaluateRepository evaluateRepository;

    @Autowired
    private ComplainRepository complainRepository;

    @Autowired
    private ContractTplRepository contractTplRepository;

    @Autowired
    private OrderLogsRepository orderLogsRepository;

    @Autowired
    private OrderPortersService orderPortersService;

    @Autowired
    private OrderPortersRepository orderPortersRepository;

    @Autowired
    private CompanyRepository companyRepository;

    @Autowired
    private DepRepository depRepository;

    @Autowired
    private WechatPayRefundService wechatPayRefundService;

    @Autowired
    private OrderAmountsService orderAmountsService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RsaService rsaService;

    @Autowired
    private UploadService uploadService;

    @Autowired
    private SmsLogService smsLogService;

    @Autowired
    private TemplateMessageService templateMessageService;

    @Value("${upload.path}")
    public String fileSavePath;
    /**
     * 患者列表
     * @return
     */
    @RequestMapping("list")
    @Transactional(rollbackFor = Exception.class)
    public ResultVo list(@RequestParam("openid") String openid) throws Exception {
        logger.error("患者列表");
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("status", QuerySpec.EQUAL,"1");
        querySpec.withMatcherValue("openid", QuerySpec.EQUAL,openid);
        List<Patient> patientList = patientRepository.findAll(QuerySpec.of(querySpec));
        logger.error("患者列表1："+patientList);
        List<PatientParam> paramList = rsaService.getPatientByOpenid(openid);
        logger.error("患者列表2："+paramList);
        if (paramList.size()>0){
            for (PatientParam patientParam : paramList){
                if (StringUtils.isNotEmpty(patientParam.getCardNo())&&StringUtils.isNotEmpty(patientParam.getPatientName())){
                    //查询绑定的患者
                    Patient patient = rsaService.getPatientInfoByCardno(patientParam.getCardNo(),patientParam.getPatientName());
                    logger.error("患者列表3："+patient);
                    if (null!=patient){
                        logger.error("患者列表4：");
                        boolean flag = true;
                        if (patientList.size()>0){
                            for (Patient patientTemp : patientList){
                                String s = IDCardEncryptor.aesDecrypt(patientTemp.getCardNo());
                                //每次访问都做更新patId
                                //查询绑定的患者
                                Patient tempPt = rsaService.getPatientInfoByCardno(s,patientTemp.getName());
                                patientTemp.setPatId(tempPt.getPatId());
                                patientTemp.setPatTypeId(tempPt.getPatTypeId());
                                patientTemp.setPatTypeName(tempPt.getPatTypeName());
                                patientRepository.save(patientTemp);
                                if (s.equals(patient.getCardNo())){
                                    flag = false;
                                    break;
                                }
                            }
                        }
                        //如果库里面没有该患者，则添加到数据库
                        if (flag){
                            //通过身份证查询
                            String s = IDCardEncryptor.aesEncrypt(patient.getCardNo());
                            QuerySpec querySpec1 = QuerySpec.matching();
                            querySpec1.withMatcherValue("status", QuerySpec.EQUAL,"1");
                            querySpec1.withMatcherValue("cardNo", QuerySpec.EQUAL,s);
                            List<Patient> patientList1 = patientRepository.findAll(QuerySpec.of(querySpec1));
                            if (patientList1.size()>0){
                                Patient patient1 = patientList1.get(0);
                                //每次访问都做更新patId
                                //查询绑定的患者
                                Patient tempPt = rsaService.getPatientInfoByCardno(patient.getCardNo(),patient1.getName());
                                patient1.setPatId(tempPt.getPatId());
                                patient1.setPatTypeId(tempPt.getPatTypeId());
                                patient1.setPatTypeName(tempPt.getPatTypeName());
                                Patient patient2 = patientRepository.save(patient1);
                                patientList.add(patient2);
                            }else{
                                patient.setOpenid(openid);
                                patient.setCardNo(s);
                                patient.setPhone(IDCardEncryptor.aesEncrypt(patient.getPhone()));
                                Patient patient1 = patientRepository.save(patient);
                                patientList.add(patient1);
                            }
                        }
                    }
                }
            }
        }
        List<Patient> tempList = new ArrayList<>();
        for (Patient patient : patientList){
            Patient patientTemp = new Patient();
            BeanUtils.copyProperties(patient,patientTemp);
            tempList.add(patientTemp);
        }
        for (Patient patient : tempList){
            patient.setCardNo(IDCardEncryptor.aesTuoMinDecrypt(patient.getCardNo()));
        }
        return ResultVoUtil.success("患者列表", tempList);
    }



    /**
     * 患者信息
     */
    @RequestMapping("info")
    public ResultVo porterDetail(@RequestParam long id) {
        Patient patient = patientRepository.findById(id).get();
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("patientId", QuerySpec.EQUAL,String.valueOf(patient.getId()))
                .withMatcherValue("admissionStatus", QuerySpec.EQUAL,"1")
                .withMatcherValue("status", QuerySpec.EQUAL,"1");
        List<PatientAdmission> patientAdmissionList = patientAdmissionRepository.findAll(QuerySpec.of(querySpec));
        if (patientAdmissionList.size()>0){
            patient.setPatientAdmission(patientAdmissionList.get(0));
        }
        return ResultVoUtil.success("患者信息", patient);
    }

    /**
     * 陪护项目列表
     */
    @GetMapping("project/list")
    public ResultVo index(@RequestParam("page") int page, @RequestParam("limit") int limit,@RequestParam("type") int type,@RequestParam("isWl") int isWl) {
        List<Object> objectList = new LinkedList<>();
        if (type==1){
            objectList.add(1);
        }else{
            objectList.add(2);
            objectList.add(3);
        }
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("verifyStatus", QuerySpec.EQUAL,"1")
                .withMatcherValue("status", QuerySpec.EQUAL,"1")
                .withMatcherValue("isWl", QuerySpec.EQUAL,String.valueOf(isWl))
                .withMatcherIn("type", objectList);
        PageRequest pageRequest = PageSort.pageRequest(1, "id", Sort.Direction.DESC);
        Page<Project> projects = projectRepository.findAll(QuerySpec.of(querySpec), pageRequest);
        List<Project> projectList = projects.getContent();
        for (Project project : projectList){
            Company company = companyRepository.findById(project.getCompanyId()).get();
            project.setCompanyName(company.getName());
            //陪护类型阶段
            QuerySpec querySpec2 = QuerySpec.matching();
            querySpec2.withMatcherValue("status", QuerySpec.EQUAL,"1")
                    .withMatcherValue("projectId", QuerySpec.EQUAL,String.valueOf(project.getId()));
            List<ProjectStage> projectStageList = projectStageRepository.findAll(QuerySpec.of(querySpec2));
            project.setProjectStageList(projectStageList);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("totalPages",projects.getTotalElements());
        map.put("list",projectList);
        return ResultVoUtil.success("陪护项目列表",map);
    }

    /**
     * 陪护项目详情
     */
    @GetMapping("project/detail")
    public ResultVo detail(@RequestParam("id") Long id) {
        Project info = projectRepository.findById(id).get();
        Company company = companyRepository.findById(info.getCompanyId()).get();
        info.setCompanyName(company.getName());
        //陪护类型阶段
        QuerySpec querySpec2 = QuerySpec.matching();
        querySpec2.withMatcherValue("status", QuerySpec.EQUAL,"1")
                .withMatcherValue("projectId", QuerySpec.EQUAL,String.valueOf(id));
        List<ProjectStage> projectStageList = projectStageRepository.findAll(QuerySpec.of(querySpec2));
        info.setProjectStageList(projectStageList);
        return ResultVoUtil.success("陪护项目详情",info);
    }

    /**
     * 科室列表
     */
    @GetMapping("dep/list")
    public ResultVo depList() {
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("status", QuerySpec.EQUAL,"1");
        List<Dep> depList = depRepository.findAll(QuerySpec.of(querySpec), Sort.by(Sort.Direction.DESC, "id"));
        return ResultVoUtil.success("科室列表",depList);
    }

    /**
     * 可接服务的护工列表
     */
    @GetMapping("porter/list")
    public ResultVo porterList(@RequestParam("page") int page, @RequestParam("limit") int limit,Porter porter) throws Exception {
        //1按阶段选择 2按小时选择
        int stageType = porter.getStageType();
        List<Object> porterList = new ArrayList<>();
        if (stageType==1){
            if (ObjectUtils.isEmpty(porter.getCompanyId())||ObjectUtils.isEmpty(porter.getNumberLimit())
                    ||ObjectUtils.isEmpty(porter.getTimeStart())||ObjectUtils.isEmpty(porter.getTimeEnd())){
                return ResultVoUtil.error("参数错误");
            }
            //查询不满足当前选择的时间内的护工
            porterList = checkPorterList(porter.getCompanyId(), porter.getNumberLimit(), porter.getTimeStart(), porter.getTimeEnd());
        }else{
            if (ObjectUtils.isEmpty(porter.getCompanyId())||ObjectUtils.isEmpty(porter.getNumberLimit())
                    ||ObjectUtils.isEmpty(porter.getTimeStart())||ObjectUtils.isEmpty(porter.getHourNum())){
                return ResultVoUtil.error("参数错误");
            }
            //计算出结束时间
            int hourNum = porter.getHourNum();
            String timeStart = porter.getTimeStart();
            String[] split = timeStart.split(":");
            int hour = Integer.parseInt(split[0]);
            int tempHour = hour+hourNum;
            String tempHourStr = (tempHour<10?"0"+tempHour:tempHour)+":"+split[1]+":00";
            porterList = checkPorterList(porter.getCompanyId(), porter.getNumberLimit(), porter.getTimeStart(), tempHourStr);
        }
        List<Object> depIds = new ArrayList<>();
        depIds.add(0);
        if (ObjectUtils.isNotEmpty(porter.getDepId())){
            depIds.add(porter.getDepId());
        }
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcher("name", QuerySpec.LIKE)
                .withMatcher("sex", QuerySpec.EQUAL)
                .withMatcher("companyId", QuerySpec.EQUAL)
                .withMatcherValue("serviceNumber", QuerySpec.LT,String.valueOf(porter.getNumberLimit()))
                .withMatcherValue("status", QuerySpec.EQUAL,"1")
                .withMatcherValue("isStatus", QuerySpec.EQUAL,"1")
                .withMatcherIn("depId", depIds);

        //判断年龄是否在范围内
        if (StringUtils.isNotEmpty(porter.getAgeStr())){
            String ageStr = porter.getAgeStr();
            if (ageStr.contains("-")){
                String[] ages = ageStr.split("-");
                querySpec.withMatcherBetween("age", Long.valueOf(ages[0]), Long.valueOf(ages[1]));
            }
        }
        //查询该科室是否有满足权限的护工
        QuerySpec queryDep = QuerySpec.matching();
        queryDep.withMatcherValue("status", QuerySpec.EQUAL,"1")
                .withMatcherValue("depId", QuerySpec.EQUAL,String.valueOf(porter.getDepId()))
                .withMatcherValue("verifyStatus", QuerySpec.EQUAL,"1");
        List<PorterPermission> permissionList = porterPermissionRepository.findAll(QuerySpec.of(queryDep));
        List<Object> porters = new ArrayList<>();
        for (PorterPermission porterPermission : permissionList){
            porters.add(porterPermission.getPorterId());
        }
        //判断是否有满足条件的护工
        if (porters.size()>0){
            querySpec.withMatcherIn("id", porters);
            if (porterList.size()>0){
                querySpec.withMatcherNotIn("id", porterList);
            }
            //排序
            Sort.Direction sort = Sort.Direction.DESC;
            if (ObjectUtils.isNotEmpty(porter.getSorts())){
                if (porter.getSorts()==2){
                    sort = Sort.Direction.ASC;
                }
            }
            PageRequest pageRequest = PageSort.pageRequest(1, "id", sort);
            Page<Porter> porterPage = porterRepository.findAll(QuerySpec.of(querySpec), pageRequest);
            List<Porter> list = porterPage.getContent();
            for (Porter info : list){
                //查询所有护理科室
                QuerySpec querySpec2 = QuerySpec.matching();
                querySpec2.withMatcherValue("status", QuerySpec.EQUAL,"1")
                        .withMatcherValue("verifyStatus", QuerySpec.EQUAL,"1")
                        .withMatcherValue("porterId", QuerySpec.EQUAL,String.valueOf(info.getId()));
                List<PorterPermission> permissionLists = porterPermissionRepository.findAll(QuerySpec.of(querySpec2));
                info.setPorterPermissions(permissionLists);
                info.setCardNo(IDCardEncryptor.aesTuoMinDecrypt(info.getCardNo()));
                info.setPhone(IDCardEncryptor.aesTuoMinPhoneDecrypt(info.getPhone()));
            }
            Map<String,Object> map = new HashMap<>();
            map.put("totalPages",porterPage.getTotalElements());
            map.put("list",list);
            return ResultVoUtil.success("可接服务的护工列表",map);
        }else{
            return ResultVoUtil.error("该科室暂无护工");
        }

    }

    /**
     * 可接服务的护工详情
     */
    @GetMapping("porter/detail")
    public ResultVo porterDetail(@RequestParam("id") Long id) throws Exception {
        Porter info = porterRepository.findById(id).get();
        //查询所有护理科室
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("status", QuerySpec.EQUAL,"1")
                .withMatcherValue("verifyStatus", QuerySpec.EQUAL,"1")
                .withMatcherValue("porterId", QuerySpec.EQUAL,String.valueOf(info.getId()));
        List<PorterPermission> permissionList = porterPermissionRepository.findAll(QuerySpec.of(querySpec));
        info.setPorterPermissions(permissionList);

        //服务次数统计
        QuerySpec querySpec1 = QuerySpec.matching();
        List<Object> statusList = new ArrayList<>();
        statusList.add(2);
        querySpec1.withMatcherValue("porterId", QuerySpec.EQUAL,String.valueOf(info.getId()))
                .withMatcherValue("status", QuerySpec.EQUAL,"1")
                .withMatcherIn("serviceStatus",statusList);
        List<OrderPorters> orderList = orderPortersRepository.findAll(QuerySpec.of(querySpec1));
        //累计服务人数
        int seviceNum = 0;
        //当前陪护人数
        int serviceNowNum = 0;
        //当前陪诊人数
        int accompanyingNum = 0;
        //当前陪检人数
        int checkNum = 0;

        for (OrderPorters order : orderList) {
            switch (order.getOrderType()){
                case 1:
                    seviceNum++;
                    serviceNowNum++;
                    break;
                case 2:
                    seviceNum++;
                    accompanyingNum++;
                    break;
                case 3:
                    seviceNum++;
                    checkNum++;
                    break;
            }

        }
        info.setServiceNowNum(serviceNowNum);
        info.setServiceNum(seviceNum);
        info.setServiceNowNum(serviceNowNum);
        info.setAccompanyingNum(accompanyingNum);
        info.setCheckNum(checkNum);

        //查询技能证书
        QuerySpec querySpec2 = QuerySpec.matching();

        //获取当前时间
        Date dates = DateUtils.getNowDate();

        querySpec2.withMatcherValue("porterId", QuerySpec.EQUAL,String.valueOf(info.getId()))
                .withMatcherValue("status", QuerySpec.EQUAL,"1");

        List<PorterCredentials> credentialsList = porterCredentialsRepository.findAll(QuerySpec.of(querySpec2));
        List<PorterCredentials> credentialsLists = new LinkedList<>();
        for (PorterCredentials porterCredentials : credentialsList) {
            if (ObjectUtils.isNotEmpty(porterCredentials.getExpireDate())){
                int compare = DateUtils.compare(porterCredentials.getExpireDate(), dates);
                if (compare == 1){
                    credentialsLists.add(porterCredentials);
                }
            }

        }
        info.setCredentials(credentialsLists);
        info.setCardNo(IDCardEncryptor.aesTuoMinDecrypt(info.getCardNo()));
        info.setPhone(IDCardEncryptor.aesTuoMinPhoneDecrypt(info.getPhone()));
        return ResultVoUtil.success("可接服务的护工详情",info);
    }

    /**
     * 选择陪护类型
     */
    @GetMapping("choose/type")
    public ResultVo choose(@RequestParam String projectId) {
        Project info = projectRepository.findById(Long.valueOf(projectId)).get();
        //陪护类型阶段
        QuerySpec querySpec2 = QuerySpec.matching();
        querySpec2.withMatcherValue("status", QuerySpec.EQUAL,"1")
                .withMatcherValue("projectId", QuerySpec.EQUAL,projectId);
        List<ProjectStage> projectStageList = projectStageRepository.findAll(QuerySpec.of(querySpec2));
        info.setProjectStageList(projectStageList);
        return ResultVoUtil.success("选择陪护类型",info);
    }

    /**
     * 判断患者是否有未完成的陪护订单
     * @param patientId
     * @return
     */
    @GetMapping("check/status")
    public ResultVo check(@RequestParam String patientId){
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("patientId", QuerySpec.EQUAL,patientId)
                .withMatcherValue("status", QuerySpec.EQUAL,"1");
        querySpec.withMatcherValue("payStatus", QuerySpec.EQUAL,"1");
        querySpec.withMatcherValue("type", QuerySpec.EQUAL,"1");
        List<Object> statusList = new ArrayList<>();
        statusList.add(0);
        statusList.add(1);
        statusList.add(2);
        statusList.add(3);
        statusList.add(4);
        querySpec.withMatcherIn("orderStatus", statusList);
        List<Order> orderList = orderRepository.findAll(QuerySpec.of(querySpec));
        Map<String,Integer> map = new HashMap<>();
        if (orderList.size()>0){
            map.put("status",1);
            return ResultVoUtil.success("该患者存在未完成的陪护订单",map);
        }else{
            map.put("status",0);
            return ResultVoUtil.success("该患者没有未完成的陪护订单",map);
        }
    }


    /**
     * 确认订单
     */
    @PostMapping("confirm/order")
    @Transactional(rollbackFor = Exception.class)
    public ResultVo order(@RequestBody Order order) throws Exception {
        if (ObjectUtils.isEmpty(order.getPatientId())){
            return ResultVoUtil.error("患者ID不能为空");
        }
        if (ObjectUtils.isEmpty(order.getProjectId())){
            return ResultVoUtil.error("项目ID不能为空");
        }
        if (ObjectUtils.isEmpty(order.getType())){
            return ResultVoUtil.error("陪护类型不能为空");
        }
        if (ObjectUtils.isEmpty(order.getCompanyId())){
            return ResultVoUtil.error("护理公司id不能为空");
        }
        if (StringUtils.isEmpty(order.getPatientName())){
            return ResultVoUtil.error("患者姓名不能为空");
        }
        //1 陪护 2 陪诊 3 陪检
        int type = order.getType();
        if (type==1){
            long patientId = order.getPatientId();
            QuerySpec querySpec22 = QuerySpec.matching();
            querySpec22.withMatcherValue("patientId", QuerySpec.EQUAL,String.valueOf(patientId))
                    .withMatcherValue("status", QuerySpec.EQUAL,"1");
            querySpec22.withMatcherValue("payStatus", QuerySpec.EQUAL,"1");
            List<Object> statusList = new ArrayList<>();
            statusList.add(0);
            statusList.add(1);
            statusList.add(2);
            statusList.add(3);
            statusList.add(4);
            querySpec22.withMatcherIn("orderStatus", statusList);
            querySpec22.withMatcherValue("type", QuerySpec.EQUAL,"1");
            List<Order> orderTempList = orderRepository.findAll(QuerySpec.of(querySpec22));
            if (orderTempList.size()>0){
                return ResultVoUtil.error("该患者存在未完成的陪护订单");
            }
        }

        Patient patient = patientRepository.findById(order.getPatientId()).get();
        order.setCardNo(patient.getCardNo());
        order.setPhone(patient.getPhone());
        //查询住院记录 获取住院记录id
        PatientAdmission patientAdmission = rsaService.getPatientAdmissionInfo(String.valueOf(order.getPatientId()),patient.getPatId(),patient.getPhone());
        //查询项目信息
        Project project = projectRepository.findById(order.getProjectId()).get();
        //判断是否为五类人员
        int isWl = patient.getIsWl();
        order.setIsWl(isWl);
        if (isWl==1){
            if (type==1){
                if (ObjectUtils.isEmpty(order.getStageType())){
                    return ResultVoUtil.error("阶段选择不能为空");
                }
                if (null == patientAdmission){
                    return ResultVoUtil.error("该住院记录不存在");
                }
                //陪护类型 1 按阶段选择 2 按小时选择
                int stageType = order.getStageType();
                //如果选择1  则查询阶段信息
                if(stageType==1){
                    if (ObjectUtils.isEmpty(order.getProjectStageId())){
                        return ResultVoUtil.error("阶段选择不能为空");
                    }
                    setOrderInfo(order,stageType,project,isWl);
                }else{
                    if (ObjectUtils.isEmpty(order.getHourNum())){
                        return ResultVoUtil.error("小时数不能为空");
                    }
                    if (StringUtils.isEmpty(order.getTimeStart())){
                        return ResultVoUtil.error("开始时间不能为空");
                    }
                    setOrderInfo(order,stageType,project,isWl);
                }
                order.setPayStatus((byte) 1);
                order.setBeforeStatus((byte) 0);
            }else{
                if (ObjectUtils.isEmpty(order.getHourNum())){
                    return ResultVoUtil.error("不允许下陪诊陪检单");
                }
                /*Double price = project.getPrice();
                order.setPrice(price);
                //扣除费用操作
                order.setNum(1);
                order.setTotal(price);
                order.setBalance(price);

                String msg = "";
                switch (type){
                    case 1:msg = "陪护";break;
                    case 2:msg = "陪诊";break;
                    case 3:msg = "陪检";break;
                }
                //新增金额变动表
                orderAmountsService.updateOrderAmounts(order,"患者"+msg+"订单缴费",2);
                //支付成功
                order.setPayStatus((byte) 1);*/
            }
            Order order1 = setTempOrderInfo(order,patientAdmission,project);
            if(type==1){
                String contents = "您有一个新的订单待确认,请及时登录后台处理。";
                //查询陪护公司管理员
                QuerySpec querySpet = QuerySpec.matching();
                querySpet.withMatcherValue("type", QuerySpec.EQUAL, "0")
                        .withMatcherValue("status", QuerySpec.EQUAL, "1");
                List<User> userList = userRepository.findAll(QuerySpec.of(querySpet));
                try {
                    if (userList.size()>0){
                        User user = userList.get(0);
                        if (StringUtils.isNotEmpty(user.getPhone())){
                            String resp = "";
                            if (user.getPhone().length()==11){
                                resp = SmsUtils.sendSms(user.getPhone(), contents);
                            }else{
                                String ss = IDCardEncryptor.aesDecrypt(user.getPhone());
                                resp = SmsUtils.sendSms(ss, contents);
                            }
                            logger.error("待确认消息发送："+resp);
                            smsLogService.insert(order1.getSn(),user.getPhone(),1,1,user.getId(),contents,resp);
                        }else{
                            smsLogService.insert(order1.getSn(),user.getPhone(),1,1,user.getId(),contents,"发送失败,手机号为空");
                        }
                    }else{
                        smsLogService.insert(order1.getSn(),"",1,1,0,contents,"发送失败,无管理员");
                    }
                } catch (Exception e) {
                    logger.error("待确认消息发送失败："+e.getMessage());
                }
            }
            return ResultVoUtil.success("确认订单",order1);
        }else{
            if (type==1){
                if (ObjectUtils.isEmpty(order.getPorterId())){
                    return ResultVoUtil.error("护工id不能为空");
                }
                Porter porter = porterRepository.findById(order.getPorterId()).get();
                //护工当前否可以继续接收服务 0否 1是
                int isStatus = porter.getIsStatus();
                if (isStatus==0){
                    return ResultVoUtil.error("该护工当前不能接单");
                }
                order.setPorterPhone(porter.getPhone());
                order.setPorterName(porter.getName());

                if (ObjectUtils.isEmpty(order.getStageType())){
                    return ResultVoUtil.error("阶段选择不能为空");
                }
                if (null == patientAdmission){
                    return ResultVoUtil.error("该住院记录不存在");
                }
                //陪护类型 1 按阶段选择 2 按小时选择
                int stageType = order.getStageType();
                //如果选择1  则查询阶段信息
                if(stageType==1){
                    if (ObjectUtils.isEmpty(order.getProjectStageId())){
                        return ResultVoUtil.error("阶段选择不能为空");
                    }
                    setOrderInfo(order,stageType,project,isWl);
                }else{
                    if (ObjectUtils.isEmpty(order.getHourNum())){
                        return ResultVoUtil.error("小时数不能为空");
                    }
                    if (StringUtils.isEmpty(order.getTimeStart())){
                        return ResultVoUtil.error("开始时间不能为空");
                    }
                    setOrderInfo(order,stageType,project,isWl);
                }

                //更新护工表限制服务人数
                porterService.updatePorter(Long.parseLong(patientAdmission.getDepId()),order.getPorterId(),project.getNumberLimit(),0,1);
                order.setPayStatus((byte) 1);
                order.setBeforeStatus((byte) 0);
            }else{
                Double price = project.getPrice();
                order.setPrice(price);
                // 回调里面 做扣除费用操作
                order.setNum(0);
                order.setTotal((double) 0);
                order.setBalance((double) 0);
                //支付成功  回调方法修改为成功
                order.setPayStatus((byte) 0);
            }
            Order order1 = setTempOrderInfo(order,patientAdmission,project);
            if(type==1){
                //更新记录
                orderPortersService.updatePorterOrder(order1.getId(),order1.getPorterId(),0L,order1.getCompanyId(),0,"","",1,order1.getType());
                String contents = "您有一个新的订单待确认,请及时登录后台处理。";
                //查询陪护公司管理员
                QuerySpec querySpet = QuerySpec.matching();
                querySpet.withMatcherValue("type", QuerySpec.EQUAL, "0")
                        .withMatcherValue("status", QuerySpec.EQUAL, "1");
                List<User> userList = userRepository.findAll(QuerySpec.of(querySpet));
                try {
                    if (userList.size()>0){
                        User user = userList.get(0);
                        if (StringUtils.isNotEmpty(user.getPhone())){
                            String resp = "";
                            if (user.getPhone().length()==11){
                                resp = SmsUtils.sendSms(user.getPhone(), contents);
                            }else{
                                String ss = IDCardEncryptor.aesDecrypt(user.getPhone());
                                resp = SmsUtils.sendSms(ss, contents);
                            }
                            logger.error("待确认消息发送："+resp);
                            smsLogService.insert(order1.getSn(),user.getPhone(),1,1,user.getId(),contents,resp);
                        }else{
                            smsLogService.insert(order1.getSn(),user.getPhone(),1,1,user.getId(),contents,"发送失败,手机号为空");
                        }
                    }else{
                        smsLogService.insert(order1.getSn(),"",1,1,0,contents,"发送失败,无管理员");
                    }
                } catch (Exception e) {
                    logger.error("待确认消息发送失败："+e.getMessage());
                }
            }
            return ResultVoUtil.success("确认订单",order1);
        }
    }

    /**
     * 取消订单
     */
    @PostMapping("cancel/order")
    @Transactional(rollbackFor = Exception.class)
    public ResultVo cancelOrder(@RequestBody Order order) throws Exception {
        if (ObjectUtils.isEmpty(order.getId())){
            return ResultVoUtil.error("订单ID不能为空");
        }
        long id = order.getId();
        Order order1 = orderRepository.getById(id);
        //1 陪护 2 陪诊 3 陪检
        int type = order1.getType();
        if (order1.getOrderStatus()>-1){
            order1.setEndTime(DateUtils.getDates());
            if (type==1) {
                //更新护工表限制服务人数
                porterService.updatePorter(0,order1.getPorterId(),order1.getNumberLimit(),order1.getId(),2);
                order1.setOrderStatus(-1);
                order1.setRemark("患者手动取消");
                orderRepository.save(order1);
                //更新记录
                orderPortersService.updatePorterOrder(order1.getId(),order1.getPorterId(),0L,order1.getCompanyId(),-1,"",DateUtils.getDates(),1,order1.getType());
                return ResultVoUtil.success("取消订单");
            }else{
                //将退还费用
                Double total = order1.getTotal();
                Double balance = order1.getBalance();
                Double refund = balance-total;
                if (refund>0){
                    PayParam payParam =  new PayParam();
                    payParam.setOutTradeNo(order1.getSn());
                    payParam.setTotalFee(String.valueOf(balance));
                    payParam.setRefundFee(String.valueOf(refund));
                    payParam.setType(1);
                    Map<String, String> msgMap = wechatPayRefundService.handleRefund(payParam);
                    String code = msgMap.get("code");
                    String msg = msgMap.get("msg");
                    order1.setOrderStatus(-1);
                    order1.setRemark("患者手动取消");
                    orderRepository.save(order1);
                    //更新记录
                    orderPortersService.updatePorterOrder(order1.getId(),order1.getPorterId(),0L,order1.getCompanyId(),-1,"",DateUtils.getDates(),1,order1.getType());
                    return ResultVoUtil.success("取消订单");
                }else{
                    order1.setOrderStatus(-1);
                    order1.setRemark("患者手动取消");
                    orderRepository.save(order1);
                    //更新记录
                    orderPortersService.updatePorterOrder(order1.getId(),order1.getPorterId(),0L,order1.getCompanyId(),-1,"",DateUtils.getDates(),1,order1.getType());
                    return ResultVoUtil.success("取消订单");
                }
            }
        }else{
            return ResultVoUtil.success("该订单已取消");
        }
    }

    /**
     * 订单列表
     */
    @GetMapping("order/list")
    public ResultVo orderList() throws Exception {
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("status", QuerySpec.EQUAL,"1")
                .withMatcherValue("payStatus", QuerySpec.EQUAL,"1")
                .withMatcher("projectTitle", QuerySpec.LIKE)
                .withMatcher("type", QuerySpec.EQUAL)
                .withMatcher("patientId", QuerySpec.EQUAL)
                .withMatcher("DATE_FORMAT(createTime, '%Y-%m-%d')", QuerySpec.EQUAL);
        PageRequest pageRequest = PageSort.pageRequest(1, "id", Sort.Direction.DESC);

        Page<Order> all = orderRepository.findAll(QuerySpec.of(querySpec), pageRequest);
        List<Order> orderList = all.getContent();
        for (Order order : orderList) {
            Long porterId = order.getPorterId();
            if (null != porterId){
                Porter porter = porterRepository.findById(porterId).get();

                //服务次数统计
                QuerySpec querySpec1 = QuerySpec.matching();
                List<Object> statusList = new ArrayList<>();
                statusList.add(1);
                statusList.add(2);
                querySpec1.withMatcherValue("porterId", QuerySpec.EQUAL,String.valueOf(porterId))
                        .withMatcherValue("status", QuerySpec.EQUAL,"1")
                        .withMatcherValue("orderType", QuerySpec.EQUAL,"1")
                        .withMatcherIn("serviceStatus",statusList);
                List<OrderPorters> orderTempList = orderPortersRepository.findAll(QuerySpec.of(querySpec1));

                //累计服务次数
                int allServiceNum = 0;
                //当前服务中次数
                int serviceNowNum = 0;
                for (OrderPorters orderPorters : orderTempList){
                    if (orderPorters.getServiceStatus()==1){
                        serviceNowNum++;
                    }else{
                        allServiceNum++;
                    }
                }

                order.setHeadimg(porter.getHeadimg());
                order.setSex(porter.getSex());
                order.setServiceNumber(serviceNowNum+"");
                String cardNo = IDCardEncryptor.aesDecrypt(porter.getCardNo());
                if (cardNo.length()>10){
                    if (!cardNo.contains("*")){
                        String substring = cardNo.substring(6,10);
                        String year = DateUtils.getYear();
                        order.setAge(Integer.parseInt(year)-Integer.parseInt(substring));
                    }else{
                        order.setAge(0);
                    }
                }else{
                    order.setAge(0);
                }
                order.setAllServiceNumber(allServiceNum+"");
            }
        }
        Map<String,Object> map = new HashMap<>();
        map.put("totalPages",all.getTotalElements());
        map.put("list",orderList);
        return ResultVoUtil.success("订单列表",map);
    }

    /**
     * 订单详情
     */
    @GetMapping("order/detail")
    public ResultVo<Order> orderDetail(@RequestParam Long id) throws Exception {
        Order info = orderRepository.findById(id).get();
        int type = info.getType();
        if (type==1){
            //护工信息
            Porter porter = porterRepository.getById(info.getPorterId());
            //服务次数统计
            QuerySpec querySpec1 = QuerySpec.matching();
            List<Object> statusList = new ArrayList<>();
            statusList.add(1);
            statusList.add(2);
            querySpec1.withMatcherValue("porterId", QuerySpec.EQUAL,String.valueOf(porter.getId()))
                    .withMatcherValue("status", QuerySpec.EQUAL,"1")
                    .withMatcherValue("orderType", QuerySpec.EQUAL,"1")
                    .withMatcherIn("serviceStatus",statusList);
            List<OrderPorters> orderList = orderPortersRepository.findAll(QuerySpec.of(querySpec1));

            //累计服务次数
            int allServiceNum = 0;
            //当前服务中次数
            int serviceNowNum = 0;
            for (OrderPorters orderPorters : orderList){
                if (orderPorters.getServiceStatus()==1){
                    serviceNowNum++;
                }else{
                    allServiceNum++;
                }
            }


            //服务次数
            info.setAllServiceNumber(allServiceNum+"");
            String cardNo = IDCardEncryptor.aesDecrypt(porter.getCardNo());
            int age = 0;
            if (cardNo.length()>10){
                String substring = cardNo.substring(6,10);
                String year = DateUtils.getYear();
                age = Integer.parseInt(year)-Integer.parseInt(substring);
            }
            info.setAge(age);

            info.setHeadimg(porter.getHeadimg());
            info.setSex(porter.getSex());
            info.setServiceNumber(serviceNowNum+"");
        }else{
            int orderStatus = info.getOrderStatus();
            //如果是已接单
            if (orderStatus>0){
                //护工信息
                Porter porter = porterRepository.getById(info.getPorterId());
                //服务次数统计
                QuerySpec querySpec1 = QuerySpec.matching();
                List<Object> statusList = new ArrayList<>();
                statusList.add(1);
                statusList.add(2);
                querySpec1.withMatcherValue("porterId", QuerySpec.EQUAL,String.valueOf(porter.getId()))
                        .withMatcherValue("status", QuerySpec.EQUAL,"1")
                        .withMatcherValue("orderType", QuerySpec.EQUAL,"1")
                        .withMatcherIn("serviceStatus",statusList);
                List<OrderPorters> orderList = orderPortersRepository.findAll(QuerySpec.of(querySpec1));

                //累计服务次数
                int allServiceNum = 0;
                //当前服务中次数
                int serviceNowNum = 0;
                for (OrderPorters orderPorters : orderList){
                    if (orderPorters.getServiceStatus()==1){
                        serviceNowNum++;
                    }else{
                        allServiceNum++;
                    }
                }
                //服务次数
                info.setAllServiceNumber(allServiceNum+"");
                String cardNo = IDCardEncryptor.aesDecrypt(porter.getCardNo());
                int age = 0;
                if (cardNo.length()>10){
                    String substring = cardNo.substring(6,10);
                    String year = DateUtils.getYear();
                    age = Integer.parseInt(year)-Integer.parseInt(substring);
                }
                info.setAge(age);

                info.setHeadimg(porter.getHeadimg());
                info.setSex(porter.getSex());
                info.setServiceNumber(serviceNowNum+"");
            }else{
                info.setAllServiceNumber(String.valueOf(0));
                info.setAge(0);

                info.setHeadimg("");
                info.setSex((byte) 0);
                info.setServiceNumber("0");
            }
        }


        Byte isNeedSignContract = info.getIsNeedSignContract();
        if (isNeedSignContract==1){
            Project project = projectRepository.getById(info.getProjectId());
            Patient patient = patientRepository.findById(info.getPatientId()).get();
            if (null != project.getContractTplId()){
                ContractTpl contractTpl = contractTplRepository.findById(project.getContractTplId()).get();
                String cardNo = IDCardEncryptor.aesTuoMinDecrypt(patient.getCardNo());
                contractTpl.setCardNo(cardNo);
                contractTpl.setName(patient.getName());
                String phone = IDCardEncryptor.aesTuoMinPhoneDecrypt(patient.getPhone());
                contractTpl.setPhone(phone);
                info.setContractTpl(contractTpl);
            }else{
                ContractTpl contractTpl = new ContractTpl();
                info.setContractTpl(contractTpl);
            }
        }
        //服务日志
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("orderId", QuerySpec.EQUAL,String.valueOf(id));
        List<OrderLogs> orderLogList = orderLogsRepository.findAll(QuerySpec.of(querySpec),Sort.by(Sort.Direction.ASC,"createDay"));
        List<TempParam> list= new ArrayList<>();
        if (orderLogList.size()>0){
            String createDay1 = orderLogList.get(0).getCreateDay();
            int m = 0;
            for (int i=0;i<orderLogList.size();i++){
                List<OrderLogs> orderLogsList = new ArrayList<>();
                for (;m<orderLogList.size();){
                    OrderLogs orderLogs = orderLogList.get(m);
                    String createDay = orderLogs.getCreateDay();
                    if (StringUtils.isNotEmpty(createDay)&&createDay1.equals(createDay)){
                        String s = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, orderLogs.getCreateTime());
                        String[] s1 = s.split(" ");
                        orderLogs.setTimes(s1[1]);
                        orderLogsList.add(orderLogs);
                        m++;
                    }else{
                        TempParam tempParam = new TempParam();
                        tempParam.setDay(createDay1);
                        tempParam.setHeadImg(orderLogs.getPorterImg());
                        tempParam.setName(orderLogs.getPorterName());
                        tempParam.setOrderLogsList(orderLogsList);
                        list.add(tempParam);
                        createDay1 = createDay;
                        break;
                    }
                }
                if (m==orderLogList.size()){
                    //最后一个补充上去
                    OrderLogs orderLogs = orderLogList.get(orderLogList.size() - 1);
                    TempParam tempParam = new TempParam();
                    tempParam.setDay(createDay1);
                    tempParam.setHeadImg(orderLogs.getPorterImg());
                    tempParam.setName(orderLogs.getPorterName());
                    tempParam.setOrderLogsList(orderLogsList);
                    list.add(tempParam);
                    break;
                }
            }
        }
        info.setTempParamList(list);
        return ResultVoUtil.success("订单详情",info);
    }

    /**
     * 结束陪护  完成订单
     */
    @PostMapping("chaperone/order")
    @Transactional(rollbackFor = Exception.class)
    public ResultVo finishOrder(@RequestBody Order order) throws Exception {
        Order order1 = orderRepository.getById(order.getId());
        int orderStatus = order1.getOrderStatus();
        //1 实时结算 2 延时结算
        int settlementType = order1.getSettlementType();
        //判断订单是否在服务中
        if (orderStatus==2){
            //将退还费用
            Double total = order1.getTotal();
            Double balance = order1.getBalance();
            Double refund = balance-total;
            if (refund>0&&settlementType==1){
                PayParam payParam =  new PayParam();
                payParam.setOutTradeNo(order1.getSn());
                payParam.setTotalFee(String.valueOf(balance));
                payParam.setRefundFee(String.valueOf(refund));
                payParam.setType(3);
                Map<String, String> msgMap = wechatPayRefundService.handleRefund(payParam);
                String code = msgMap.get("code");
                String msg = msgMap.get("msg");
                //更新订单状态
                order1.setOrderStatus(5);
                order1.setEndTime(DateUtils.getDates());
                //更新护工表限制服务人数
                porterService.updatePorter(0,order1.getPorterId(),order1.getNumberLimit(),order1.getId(),2);
                orderRepository.save(order1);
                //更新记录
                orderPortersService.updatePorterOrder(order1.getId(),order1.getPorterId(),0L,order1.getCompanyId(),2,"",DateUtils.getDates(),1,order1.getType());
                return ResultVoUtil.success("结束陪护",order);
            }else{
                //更新订单状态
                order1.setOrderStatus(5);
                order1.setEndTime(DateUtils.getDates());
                //更新护工表限制服务人数
                porterService.updatePorter(0,order1.getPorterId(),order1.getNumberLimit(),order1.getId(),2);
                orderRepository.save(order1);
                //更新记录
                orderPortersService.updatePorterOrder(order1.getId(),order1.getPorterId(),0L,order1.getCompanyId(),2,"",DateUtils.getDates(),1,order1.getType());
                return ResultVoUtil.success("结束陪护",order);
            }
        }else{
            return ResultVoUtil.success("订单不在服务中",order);
        }
    }

    /**
     * 手动点击服务完成(针对陪诊陪检)
     * @param order
     * @return
     */
    @PostMapping("finish/order")
    @Transactional(rollbackFor = Exception.class)
    public ResultVo finishPorter(@RequestBody Order order) throws Exception {
        Order order1 = orderRepository.getById(order.getId());
        //将退还费用
        Double total = order1.getTotal();
        Double balance = order1.getBalance();
        Double refund = balance-total;
        if (refund>0){
            PayParam payParam =  new PayParam();
            payParam.setOutTradeNo(order1.getSn());
            payParam.setTotalFee(String.valueOf(balance));
            payParam.setRefundFee(String.valueOf(refund));
            payParam.setType(4);
            Map<String, String> msgMap = wechatPayRefundService.handleRefund(payParam);
            String code = msgMap.get("code");
            String msg = msgMap.get("msg");
            order1.setOrderStatus(5);
            order1.setEndTime(DateUtils.getDates());
            orderRepository.save(order1);
            //更新记录
            orderPortersService.updatePorterOrder(order1.getId(),order1.getPorterId(),0L,order1.getCompanyId(),2,"",DateUtils.getDates(),1,order1.getType());
            return ResultVoUtil.success("服务完成",order);
        }else{
            order1.setOrderStatus(5);
            order1.setEndTime(DateUtils.getDates());
            orderRepository.save(order1);
            //更新记录
            orderPortersService.updatePorterOrder(order1.getId(),order1.getPorterId(),0L,order1.getCompanyId(),2,"",DateUtils.getDates(),1,order1.getType());
            return ResultVoUtil.success("服务完成",order);
        }
    }

    /**
     * 评价护工
     */
    @PostMapping("evaluate/porter")
    @Transactional(rollbackFor = Exception.class)
    public ResultVo evaluatePorter(@RequestBody Evaluate evaluate) throws Exception {
        Porter porter = porterRepository.findById(evaluate.getPorterId()).get();
        evaluate.setName(porter.getName());
        evaluate.setSex(porter.getSex());
        evaluate.setHeadimg(porter.getHeadimg());
        evaluate.setCardNo(porter.getCardNo());
        String cardNo = IDCardEncryptor.aesDecrypt(porter.getCardNo());
        int age = 0;
        if (cardNo.length()>10){
            String substring = cardNo.substring(6,10);
            String year = DateUtils.getYear();
            age = Integer.parseInt(year)-Integer.parseInt(substring);
        }
        evaluate.setAge(age);
        evaluate.setPhone(porter.getPhone());
        evaluate.setCompanyId(porter.getCompanyId());

        //同时更新护工评分
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("porterId", QuerySpec.EQUAL,String.valueOf(evaluate.getPorterId()))
                .withMatcherValue("status", QuerySpec.EQUAL,String.valueOf(1));
        PageRequest pageRequest = PageRequest.of(0, 9, Sort.by(Sort.Direction.DESC, "id"));
        List<Evaluate> evaluateList = evaluateRepository.findAll(QuerySpec.of(querySpec), pageRequest).getContent();
        int score = 0;
        if (evaluateList.size()>0){
            for (Evaluate evaluate1 : evaluateList) {
                score += evaluate1.getScore();
            }
        }
        int score1 = evaluate.getScore();
        score += score1;
        if (evaluateList.size()==9){
            porter.setScore(score/10);
        }else{
            porter.setScore(score/(evaluateList.size()+1));
        }

        //更新评分
        porterRepository.save(porter);

        QuerySpec querySpec1 = QuerySpec.matching();
        querySpec1.withMatcherValue("sn", QuerySpec.EQUAL,String.valueOf(evaluate.getSn()))
                .withMatcherValue("status", QuerySpec.EQUAL,String.valueOf(1));
        Order order = orderRepository.findAll(QuerySpec.of(querySpec1)).get(0);
        order.setOrderStatus(6);
        order.setEvaluateStatus((byte) 1);
        //更新订单
        orderRepository.save(order);
        //更新评价
        evaluate.setStatus((byte) 1);
        evaluate.setPatientName(order.getPatientName());
        evaluate.setOrderType(order.getType());
        evaluateRepository.save(evaluate);
        return ResultVoUtil.success("评价护工",evaluate);
    }


    /**
     * 投诉
     */
    @PostMapping("complain")
    public ResultVo complain(@RequestBody Complain complain) throws Exception {
        Porter porter = porterRepository.findById(complain.getPorterId()).get();
        complain.setName(porter.getName());
        complain.setSex(porter.getSex());
        complain.setHeadimg(porter.getHeadimg());
        complain.setCardNo(porter.getCardNo());
        String cardNo = IDCardEncryptor.aesDecrypt(porter.getCardNo());
        int age = 0;
        if (cardNo.length()>10){
            String substring = cardNo.substring(6,10);
            String year = DateUtils.getYear();
            age = Integer.parseInt(year)-Integer.parseInt(substring);
        }
        complain.setAge(age);
        complain.setStatus((byte) 1);

        QuerySpec querySpec1 = QuerySpec.matching();
        querySpec1.withMatcherValue("sn", QuerySpec.EQUAL,String.valueOf(complain.getSn()))
                .withMatcherValue("status", QuerySpec.EQUAL,String.valueOf(1));
        Order order = orderRepository.findAll(QuerySpec.of(querySpec1)).get(0);
        order.setComplainStatus((byte) 1);

        complain.setCompanyId(order.getCompanyId());
        //更新订单
        orderRepository.save(order);

        complainRepository.save(complain);
        return ResultVoUtil.success("投诉成功",complain);
    }

    /**
     * 查看评价详情
     */
    @GetMapping("check/evaluate")
    public ResultVo checkEvaluate(@RequestParam String sn){
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("sn", QuerySpec.EQUAL,sn)
                .withMatcherValue("status", QuerySpec.EQUAL,String.valueOf(1));
        List<Evaluate> evaluateList = evaluateRepository.findAll(QuerySpec.of(querySpec));
        if (evaluateList.size()>0){
            Evaluate evaluate = evaluateList.get(0);
            Date createTime = evaluate.getCreateTime();
            evaluate.setCreateTimeStr(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,createTime));
            return ResultVoUtil.success("评价详情",evaluateList.get(0));
        }else{
            return ResultVoUtil.error("未评价");
        }
    }

    /**
     * 查看投诉详情
     */
    @GetMapping("check/complain")
    public ResultVo checkComplain(@RequestParam String sn){
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("sn", QuerySpec.EQUAL,sn)
                .withMatcherValue("status", QuerySpec.EQUAL,String.valueOf(1));
        List<Complain> complainList = complainRepository.findAll(QuerySpec.of(querySpec));
        if (complainList.size()>0){
            return ResultVoUtil.success("投诉详情",complainList.get(0));
        }else{
            return ResultVoUtil.error("未投诉");
        }
    }



    /**
     * 首页住院信息
     */
    @GetMapping("hospitalized/info")
    public ResultVo hospitalized(@RequestParam long patientId) throws Exception {
        Patient patient = patientRepository.findById(patientId).get();
        PatientAdmission patientAdmissionInfo = rsaService.getPatientAdmissionInfo(String.valueOf(patientId), patient.getPatId(),patient.getPhone());
        if (null!=patientAdmissionInfo){
            setPatientAdmissionInfo(patientAdmissionInfo,patientId);
            return ResultVoUtil.success("住院信息",patientAdmissionInfo);
        }else{
            return ResultVoUtil.success("该患者未住院");
        }
    }


    /**
     * 推荐护工列表
     */
    @GetMapping("recommend/porter/list")
    public ResultVo recommendPorterList(Porter porter) {
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("status", QuerySpec.EQUAL,String.valueOf(1))
                .withMatcher("name", QuerySpec.LIKE)
                .withMatcher("sex", QuerySpec.EQUAL);
        Sort.Direction desc = Sort.Direction.DESC;

        if (ObjectUtils.isNotEmpty(porter.getSorts())){
            if (porter.getSorts()==1){
                desc = Sort.Direction.DESC;
            }else{
                desc = Sort.Direction.ASC;
            }
        }
        //判断年龄是否在范围内
        if (StringUtils.isNotEmpty(porter.getAgeStr())){
            String ageStr = porter.getAgeStr();
            if (ageStr.contains("-")){
                String[] ages = ageStr.split("-");
                querySpec.withMatcherBetween("age", Long.valueOf(ages[0]), Long.valueOf(ages[1]));
            }
        }
        //查询科室
        if (ObjectUtils.isNotEmpty(porter.getDepId())){
            QuerySpec queryDep = QuerySpec.matching();
            queryDep.withMatcherValue("status", QuerySpec.EQUAL,"1")
                    .withMatcherValue("depId", QuerySpec.EQUAL,String.valueOf(porter.getDepId()))
                    .withMatcherValue("verifyStatus", QuerySpec.EQUAL,"1");
            List<PorterPermission> permissionTempList = porterPermissionRepository.findAll(QuerySpec.of(queryDep));
            List<Object> porterTemps = new ArrayList<>();
            for (PorterPermission porterPermission : permissionTempList){
                porterTemps.add(porterPermission.getPorterId());
            }
            if (porterTemps.size()>0){
                querySpec.withMatcherIn("id", porterTemps);
                PageRequest pageRequest = PageSort.pageRequest(1, "score", desc);
                Page<Porter> all = porterRepository.findAll(QuerySpec.of(querySpec), pageRequest);
                List<Porter> porterList = all.getContent();
                for (Porter porters : porterList){
                    //服务次数统计
                    QuerySpec querySpec1 = QuerySpec.matching();
                    List<Object> statusList = new ArrayList<>();
                    statusList.add(2);
                    querySpec1.withMatcherValue("porterId", QuerySpec.EQUAL,String.valueOf(porters.getId()))
                            .withMatcherValue("status", QuerySpec.EQUAL,"1")
                          //  .withMatcherValue("orderType", QuerySpec.EQUAL,"1")
                            .withMatcherIn("serviceStatus",statusList);
                    List<OrderPorters> orderList = orderPortersRepository.findAll(QuerySpec.of(querySpec1));
                    //服务次数
                    porters.setServiceNum(orderList.size());

                    //查询所有护理科室
                    QuerySpec querySpec2 = QuerySpec.matching();
                    querySpec2.withMatcherValue("status", QuerySpec.EQUAL,"1")
                            .withMatcherValue("verifyStatus", QuerySpec.EQUAL,"1")
                            .withMatcherValue("porterId", QuerySpec.EQUAL,String.valueOf(porters.getId()));
                    List<PorterPermission> permissionList = porterPermissionRepository.findAll(QuerySpec.of(querySpec2));
                    porters.setPorterPermissions(permissionList);
                }
                Map<String,Object> map = new HashMap<>();
                map.put("totalPages",all.getTotalElements());
                map.put("list",porterList);
                return ResultVoUtil.success("推荐护工列表",map);
            }else{
                Map<String,Object> map = new HashMap<>();
                map.put("totalPages",0);
                map.put("list",new ArrayList<Porter>());
                return ResultVoUtil.success("推荐护工列表",map);
            }
        }else{
            PageRequest pageRequest = PageSort.pageRequest(1, "score", desc);
            Page<Porter> all = porterRepository.findAll(QuerySpec.of(querySpec), pageRequest);
            List<Porter> porterList = all.getContent();
            for (Porter porters : porterList){
                //服务次数统计
                QuerySpec querySpec1 = QuerySpec.matching();
                List<Object> statusList = new ArrayList<>();
                statusList.add(2);
                querySpec1.withMatcherValue("porterId", QuerySpec.EQUAL,String.valueOf(porters.getId()))
                        .withMatcherValue("status", QuerySpec.EQUAL,"1")
                       // .withMatcherValue("orderType", QuerySpec.EQUAL,"1")
                        .withMatcherIn("serviceStatus",statusList);
                List<OrderPorters> orderList = orderPortersRepository.findAll(QuerySpec.of(querySpec1));
                //服务次数
                porters.setServiceNum(orderList.size());

                //查询所有护理科室
                QuerySpec querySpec2 = QuerySpec.matching();
                querySpec2.withMatcherValue("status", QuerySpec.EQUAL,"1")
                        .withMatcherValue("verifyStatus", QuerySpec.EQUAL,"1")
                        .withMatcherValue("porterId", QuerySpec.EQUAL,String.valueOf(porters.getId()));
                List<PorterPermission> permissionList = porterPermissionRepository.findAll(QuerySpec.of(querySpec2));
                porters.setPorterPermissions(permissionList);
            }
            Map<String,Object> map = new HashMap<>();
            map.put("totalPages",all.getTotalElements());
            map.put("list",porterList);
            return ResultVoUtil.success("推荐护工列表",map);
        }
    }


    /**
     * 消息列表
     */
    @GetMapping("msg")
    public ResultVo msg() {
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcher("patientId", QuerySpec.EQUAL);
        PageRequest pageRequest = PageSort.pageRequest(1, "id", Sort.Direction.DESC);
        Page<Msg> all = msgRepository.findAll(QuerySpec.of(querySpec), pageRequest);
        List<Msg> msgList = all.getContent();
        for (Msg msg : msgList){
            msg.setCreateTimeStr(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, msg.getCreateTime()));
        }
        Map<String,Object> map = new HashMap<>();
        map.put("totalPages",all.getTotalElements());
        map.put("list",msgList);
        return ResultVoUtil.success("消息列表",map);
    }

    /**
     * 结算记录
     */
    @GetMapping("admission/list")
    public ResultVo patientAdmission(@RequestParam long patientId) {
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("patientId", QuerySpec.EQUAL,String.valueOf(patientId))
                .withMatcherValue("status", QuerySpec.EQUAL,"1")
                .withMatcherValue("admissionStatus", QuerySpec.EQUAL,"2")
                .withMatcher("dischargeTime", QuerySpec.LIKE);
        PageRequest pageRequest = PageSort.pageRequest(1, "id", Sort.Direction.DESC);
        Page<PatientAdmission> all = patientAdmissionRepository.findAll(QuerySpec.of(querySpec), pageRequest);
        List<PatientAdmission> admissionList = all.getContent();
        for (PatientAdmission patientAdmission : admissionList){
            QuerySpec querySpec1 = QuerySpec.matching();
            querySpec1.withMatcherValue("status", QuerySpec.EQUAL,"1")
                    .withMatcherValue("patientAdmissionId", QuerySpec.EQUAL,String.valueOf(patientAdmission.getId()));
            List<Order> orderList = orderRepository.findAll(QuerySpec.of(querySpec1));
            //查询该患者住院期间订单合计费用
            double total = 0;
            for (Order order : orderList){
                total += order.getTotal();
            }
            patientAdmission.setUsedMoney(total);
        }

        Map<String,Object> map = new HashMap<>();
        map.put("totalPages",all.getTotalElements());
        map.put("list",admissionList);
        return ResultVoUtil.success("结算记录",map);
    }

    /**
     * 结算详情
     */
    @GetMapping("admission/detail")
    public ResultVo patientAdmissionDetail(@RequestParam long id) {
        PatientAdmission patientAdmission = patientAdmissionRepository.findById(id).get();

        //查询该患者住院期间的订单
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("status", QuerySpec.EQUAL,"1")
                .withMatcherValue("payStatus", QuerySpec.EQUAL,"1")
                .withMatcherValue("patientAdmissionId", QuerySpec.EQUAL,String.valueOf(id))
                .withMatcherValue("orderStatus", QuerySpec.GT,"4");
        List<Order> orderList = orderRepository.findAll(QuerySpec.of(querySpec),Sort.by(Sort.Direction.ASC,"id"));
        //查询该患者住院期间订单合计费用
        double total = 0;
        double useMoney = 0;
        List<Object> orderIdsList = new ArrayList<>();
        for (Order order : orderList){
            Company company = companyRepository.findById(order.getCompanyId()).get();
            order.setCompanyName(company.getName());
            total += order.getBalance();
            useMoney += order.getTotal();
            orderIdsList.add(order.getId());
        }
        QuerySpec querySpec1 = QuerySpec.matching();
        querySpec1.withMatcherValue("type", QuerySpec.EQUAL,"1")
                .withMatcherValue("status", QuerySpec.EQUAL,"1")
                .withMatcherIn("orderId",orderIdsList);
        List<OrderAmounts> orderAmountsList = orderAmountsRepository.findAll(QuerySpec.of(querySpec1), Sort.by(Sort.Direction.ASC, "createDay"));
        List<TempParam> list= new ArrayList<>();
        if (orderAmountsList.size()>0){
            String createDay1 = orderAmountsList.get(0).getCreateDay();
            int m = 0;
            for (int i=0;i<orderAmountsList.size();i++){
                List<Order> orderTempList = new ArrayList<>();
                for (;m<orderAmountsList.size();){
                    OrderAmounts orderAmounts = orderAmountsList.get(m);
                    String createDay = orderAmounts.getCreateDay();
                    if (StringUtils.isNotEmpty(createDay)&&createDay1.equals(createDay)){
                        for (Order order : orderList){
                            if (Objects.equals(order.getId(), orderAmounts.getOrderId())){
                                orderTempList.add(order);
                                break;
                            }
                        }
                        m++;
                    }else{
                        TempParam tempParam = new TempParam();
                        tempParam.setDay(createDay1);
                        tempParam.setOrderList(orderTempList);
                        list.add(tempParam);
                        createDay1 = createDay;
                        break;
                    }
                }
                if (m==orderAmountsList.size()){
                    //最后一个补充上去
                    TempParam tempParam = new TempParam();
                    tempParam.setDay(createDay1);
                    tempParam.setOrderList(orderTempList);
                    list.add(tempParam);
                    break;
                }
            }
        }
        patientAdmission.setTotal(total);
        patientAdmission.setUsedMoney(useMoney);
        patientAdmission.setTempParamList(list);
        return ResultVoUtil.success("结算详情",patientAdmission);
    }

    /**
     * 文件上传
     */
    @PostMapping("/upload/image")
    @ResponseBody
    public ResultVo uploadImage(@RequestParam("image") MultipartFile multipartFile) throws IOException {

        // 创建Upload实体对象
        Upload upload = uploadService.inserts(multipartFile,fileSavePath);
        return ResultVoUtil.success("上传成功",upload);
    }


    /**
     * 根据身份证姓名获取患者信息
     */
    @GetMapping("hz/info")
    public ResultVo patientByCardNo(String cardNo,String name,String openid) throws Exception {
        JSONArray data = rsaService.getPatInfo();
        return ResultVoUtil.success("居民类别信息",data);
    }

    @GetMapping("adminssion/info")
    public ResultVo patientById(String patientId) throws Exception {
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("patientId", QuerySpec.EQUAL, patientId)
                .withMatcherValue("status", QuerySpec.EQUAL, "1");
        List<PatientAdmission> patientAdmissionList = patientAdmissionRepository.findAll(QuerySpec.of(querySpec));
        if (patientAdmissionList.size()>0){
            PatientAdmission patientAdmission = patientAdmissionList.get(0);
            String body = rsaService.getPatientCyAdmissionInfo(patientAdmission);
            return ResultVoUtil.success("患者出院信息",body);
        }
        return ResultVoUtil.success("患者出院信息","");
    }

    @GetMapping("op/info")
    public ResultVo opInfo(String cardNo,String name) throws Exception {
        Patient result = rsaService.getPatientInfoByCardno(cardNo,name);

        return ResultVoUtil.success("获取患者信息",result);
    }

    @GetMapping("dep/info")
    public ResultVo depInfo(String patientId) throws Exception {
       List<Dep> result = rsaService.getDepIdList();
        return ResultVoUtil.success("科室基本信息",result);
    }




    private List<Object> checkPorterList(long companyId,int numberLimit,String timeStart,String timeEnd){
        List<Object> tempList = orderRepository.checkOrderList(timeStart,companyId,timeEnd);
        List<Object> porterIdList = new LinkedList<>();
        for (Object o : tempList) {
            Object[] objects = (Object[]) o;
            long num = (Long) objects[0];
            long projectId = (Long) objects[1];
            int numberLimitTemp = (Integer) objects[2];
            long porterId = (long) objects[3];
            //如果服务数大于等于限制数 则记录
            if (num>=numberLimit){
                porterIdList.add(porterId);
            }
        }

        return porterIdList;
    }
    private void setPatientAdmissionInfo(PatientAdmission patientAdmission,long patientId){
        QuerySpec querySpec1 = QuerySpec.matching();
        //查询该患者住院期间的订单
        querySpec1.withMatcherValue("status", QuerySpec.EQUAL,"1")
                .withMatcherValue("payStatus", QuerySpec.EQUAL,"1")
                .withMatcherValue("patientId", QuerySpec.EQUAL,String.valueOf(patientId))
                .withMatcherValue("orderStatus", QuerySpec.GT,"-1");
        List<Order> orderList = orderRepository.findAll(QuerySpec.of(querySpec1),Sort.by(Sort.Direction.DESC,"id"));
        //统计金额
        BigDecimal total = new BigDecimal(0);
        BigDecimal usedMoney = new BigDecimal(0);
        BigDecimal refundMoney = new BigDecimal(0);
        for (Order order : orderList) {
            Double balance = order.getBalance();
            Double total1 = order.getTotal();
            BigDecimal totalTemp = new BigDecimal(balance);
            BigDecimal usedMoneyTemp = new BigDecimal(total1);
            total = total.add(totalTemp);
            usedMoney = usedMoney.add(usedMoneyTemp);
            //计算已退款的金额
            if (order.getRefundStatus()==2){
                BigDecimal stt = totalTemp.subtract(usedMoneyTemp);
                refundMoney = refundMoney.add(stt);
            }
            //查询公司
            Company company = companyRepository.findById(order.getCompanyId()).get();
            order.setCompanyName(company.getName());
        }
        patientAdmission.setTotal(total.doubleValue());
        patientAdmission.setUsedMoney(usedMoney.doubleValue());
        patientAdmission.setRefundMoney(refundMoney.doubleValue());

        patientAdmission.setOrderList(orderList);
    }

    private void setOrderInfo(Order order,int stageType,Project project,int isWl){
        //如果选择1  则查询阶段信息
        if(stageType==1){
            //查询项目阶段
            ProjectStage projectStage = projectStageRepository.findById(order.getProjectStageId()).get();
            Double price = projectStage.getPrice();
            order.setPrice(price);
            order.setTimeStart(projectStage.getTimeStart());
            order.setTimeEnd(projectStage.getTimeEnd());
            order.setProjectStageName(projectStage.getTitle());
            order.setNum(0);
            order.setTotal((double) 0);
            order.setBalance((double) 0);
            String timeStart = order.getTimeStart();
            String[] split = timeStart.split(":");
            String timeEnd = order.getTimeEnd();
            String[] splits = timeEnd.split(":");
            int hour = Integer.parseInt(split[0]);
            int endHour = Integer.parseInt(splits[0]);
            //判断是否跨日
            int transDay = 0;
            if (endHour<=hour){
                transDay = 1;
            }
            order.setTransDay(transDay);

        }else{
            //计算出结束时间
            int hourNum = order.getHourNum();
            String timeStart = order.getTimeStart();
            String[] split = timeStart.split(":");
            int hour = Integer.parseInt(split[0]);
            int tempHour = hour+hourNum;
            String tempHourStr = (tempHour<10?"0"+tempHour:tempHour)+":"+split[1]+":00";
            //设置虚拟结束时间
            order.setTimeEndTemp(tempHourStr);
            //判断是否跨日
            int transDay = 0;
            //判断是否超过0点 超过0点则减去24小时
            if (tempHour>24){
                tempHour = tempHour-24;
                transDay = 1;
            }
            String timeEnd = (tempHour<10?"0"+tempHour:tempHour)+":"+split[1]+":00";
            order.setTransDay(transDay);
            order.setTimeEnd(timeEnd);
            order.setPrice(project.getPrice());
            order.setNum(0);
            order.setTotal((double) 0);
            order.setBalance((double) 0);
        }
    }

    private Order setTempOrderInfo(Order order,PatientAdmission patientAdmission,Project project){
        //判断是否有住院记录
        if (null != patientAdmission){
            order.setPatientAdmissionId(patientAdmission.getId());
            order.setDepId(patientAdmission.getDepId());
            order.setBedNo(patientAdmission.getBedNo());
            order.setDepName(patientAdmission.getDepName());
            order.setAdmissionTime(patientAdmission.getAdmissionTime());
            order.setAdmissionStatus(1);
        }else{
            order.setAdmissionStatus(0);
        }
        //项目当前服务人数限制
        order.setNumberLimit(project.getNumberLimit());
        //是否需要签订合同
        order.setIsNeedSignContract(project.getIsNeedSignContract());
        order.setOrderStatus(0);
        order.setProjectTitle(project.getTitle());

        //生成订单号
        SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
        long l = idGenerator.nextId();
        order.setSn("NO"+l);

        order.setSettlementType(0);
        order.setIsSettled(0);
        order.setSettledType(0);
        order.setComplainStatus((byte) 0);
        order.setEvaluateStatus((byte) 0);
        order.setStatus((byte) 1);
        order.setRefundStatus((byte) 0);
        Order order1 = orderRepository.save(order);
        return order1;
    }
}
